<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="studentsObj.name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="studentsObj.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="studentsObj.gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add_modify">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <thead>
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in students" :key="item.id">
            <td>{{ index + 1 }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.gender }}</td>
            <td>
              <button @click="del(index)">删除</button>
              <button @click="edit(index)">编辑</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      editIndex: null,
      studentsObj: {
        name: "",
        age: "",
        gender: "",
      },
      students: [
        { id: 1, name: "Yu", age: 26, gender: "男" },
        { id: 2, name: "Sam", age: 27, gender: "男" },
        { id: 3, name: "Together", age: 11, gender: "女" },
      ],
    };
  },
  methods: {
    del(i) {
      this.students.splice(i, 1);
    },
    edit(i) {
      this.editIndex = i;
      console.log(this.editIndex);
      this.studentsObj = { ...this.students[i] };
    },
    add_modify() {
      //必须用浅拷贝
      let theObj = { ...this.studentsObj };
      if (this.editIndex !== null) {
        //修改
        this.$set(this.students, this.editIndex, theObj);
        this.editIndex = null;
        this.studentsObj.name = this.studentsObj.age = this.studentsObj.gender =
          "";
      } else {
        if (!theObj.name || !theObj.age || !theObj.gender)
          return alert("信息不能为空");
        this.students.push(theObj);
        this.studentsObj.name = this.studentsObj.age = this.studentsObj.gender =
          "";
      }
    },
  },
};
</script>
